﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;

namespace HostEdit
{
    public class Hosts : IndexedObservableCollection<Host, String>,  INotifyPropertyChanged
    {

        public Hosts(): base(c  => c.Name)
        { 
        
        }


        private string _Name;
        public String Name
        {
            get
            {
                return _Name;
            }
            set
            {
                if (_Name == value) return;
                _Name = value;
                if (PropertyChanged != null) PropertyChanged(this, new PropertyChangedEventArgs("Name"));
            }
        }

        public event PropertyChangedEventHandler PropertyChanged;

        public Entries Save()
        {
            Entries p = new Entries { Name = this.Name };
            p.Hosts = new List<Entry>();
            foreach (Host i in this.OrderBy( c => c.Name))
                p.Hosts.AddRange(i.Save());             
            return p;
        }


        public void Load(Entries ent)
        {
            
            Name = ent.Name;

            foreach (Entry e in ent.Hosts)
            {
                if (!this.Contains(e.Host) )
                    this.Add( new Host() { Name = e.Host } );

                Host h = this.Get(e.Host);

                if (!h.Address.Contains(e.Ip))
                    h.Address.Add(new Adress() { Active = e.Active, Host = h, Value = e.Ip });
                
            }
           
           
        }

    }
}
